<?php

declare(strict_types=1);
/**
 * This file is part of bearing-web.
 *
 * @link     https://www.bearing.cn/
 * @contact  tech@bearing.cn
 * @license  https://gitee.com/cppo/bearing_web/-/blob/master/README.md
 */

namespace frontend\actions;

use common\models\ProductDetailModel;
use common\models\ProductModel;
use yii\rest\ViewAction;
use yii\web\NotFoundHttpException;

class ProductViewAction extends ViewAction
{
    /**
     * @param $id
     * @return array
     * @throws NotFoundHttpException
     */
    public function run($id): array
    {
        $model = $this->findModel($id);
        if ($this->checkAccess) {
            call_user_func($this->checkAccess, $this->id, $model);
        }
        if (! $model instanceof ProductModel || ! $model->id) {
            return [];
        }
        return [
            'id' => $model->id,
            'name' => $model->name,
            'create_time' => $model->create_time,
            'price' => $model->price,
            'cate_id' => $model->cate_id,
            'thumb' => $model->thumb,
            'attr' => $this->getProductAttr($model->id),
        ];
    }

    private function getProductAttr(int $productId = 0)
    {
        $attr = [];
        if (! $productId) {
            return $attr;
        }

        $model = ProductDetailModel::findOne(['product_id' => $productId]);
        if ($model instanceof ProductDetailModel && $model->id) {
            if ($model->attr) {
                $attr = json_decode($model->attr, true);
            }
        }
        unset($attr['cate_id'],$attr['bearing_type'],$attr['product_id'],$attr['product_no']);
        return $attr;
    }
}
